import random
from django.contrib.auth import get_user_model
from rest_framework import mixins, viewsets, status
from django.contrib.auth.backends import ModelBackend
from django.db.models.query import Q
from rest_framework.response import Response
from rest_framework_jwt.serializers import jwt_encode_handler, jwt_payload_handler

from .models import VerifyCode
from .serializers import SmsSerializer, UserRegSerializer
from utils.yunpian import YunPian
from Outback.settings import APIKEY

User = get_user_model()


class CustomBackend(ModelBackend):
    """
    自定义验证类，可以用用户名和邮箱和手机登录
    """

    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = User.objects.get(Q(username=username) | Q(email=username) | Q(mobile=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None


class SmsCodeViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet):
    """
    create:
        生成验证码
    """
    serializer_class = SmsSerializer

    def generate_code(self, n=4):
        seed = '1234567890'
        return ''.join([random.choice(seed) for _ in range(n)])

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        mobile = serializer.validated_data['mobile']
        code = self.generate_code(n=4)
        yunpian = YunPian(APIKEY)
        sms_status = yunpian.send_sms(code=code, mobile=mobile)
        if sms_status['code'] != 0:
            return Response({
                'mobile': sms_status['msg']
            }, status=status.HTTP_400_BAD_REQUEST)
        else:
            verifycode = VerifyCode(code=code, mobile=mobile)
            verifycode.save()
            return Response({
                'mobile': mobile
            }, status=status.HTTP_201_CREATED)


class UserViewSet(mixins.CreateModelMixin,mixins.UpdateModelMixin, viewsets.GenericViewSet):
    """
    create:
        创建用户（用户注册）
    """
    serializer_class = UserRegSerializer
    queryset = User.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = self.perform_create(serializer)
        res_dict = serializer.data
        payload = jwt_payload_handler(user)
        res_dict['token'] = jwt_encode_handler(payload)
        res_dict['name'] = user.name if user.name else user.username
        headers = self.get_success_headers(serializer.data)
        return Response(res_dict, status=status.HTTP_201_CREATED, headers=headers)

    def perform_create(self, serializer):
        user = serializer.save()
        return user